var express = require('express');
var router = express.Router();
var {
  user_model
} = require('../utils/model')
var {
  aesEncrypt
} = require("../utils")
/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});
router.get('/demo', function (req, res) {
  res.send('<h2>are you ok ?</h2>')
})

router.get('/data', function (req, res) {
  res.json({
    code: 200,
    type: 1,
    msg: '获取数据成功--users'
  })
})

router.all('/login', function (req, res) {
  var query = req.query
  // console.log(query.password);
  user_model.findOne({
    username: query.username
  }).then(result => {
    if (result) {

      if (result.pass == query.pass) {
        req.session.username = result.username 
        req.session.phone = result.phone
        res.redirect("/")
        // res.send("<script>alert('登陆成功')</script>");
      } else {
        res.send("<script>alert('登陆失败,用户名和密码不匹配');location.href='/login'</script>")
      }
    } else {
      res.send("<script>alert('当前用户不存在');location.href='/login'</script>")
    }

  })

})

router.all('/register', function (req, res) {
  var body = req.body
  // console.log(body);

  // 插入注册
  user_model.findOne({
    username: body.username
  }).then(data => {
    // console.log(data);

    if (data) {
      res.send("<script>alert('当前用户已经被注册,请重新注册!');location.href='/register'</script>")
    } else {
      body.time = new Date()
      user_model.insertMany(body)
        .then(result => {
          res.send(`<script>alert('注册成功，前往登录!');location.href='/login?username=${aesEncrypt(body.username)}'</script>`)
        })
    }
  }).catch(err => {

  })

})
// ajax 最好返回json 
router.all('/signin', (req, res) => {
  var body = req.body
  user_model.findOne({
      ...body
    })
    .then(result => {
      if (result) {
        res.json({
          code: 200,
          msg: '登录成功',
          body,
          result
        })
      } else {
        res.json({
          code: 1001,
          msg: '登陆失败'
        })
      }

    }) .catch(err=>{
      res.json({
        code:500,
        msg:'服务器异常',
        err
      })
    })
})

module.exports = router;